package com.cats.bi.sqltool.function;


import com.cats.bi.sqltool.SQLString;
import com.cats.bi.sqltool.basic.AbstractColumn;

/**
 * @Description
 * @author wang jian
 * @create 2021/4/7
 */
public class Expression extends AbstractColumn<Expression> {
    private static final char[] SYMBOL = {'+', '-', '*', '/', '%', '(', ')', '|', '>', '<', '='};
    private Object[] objs;

    /**
     * @param objs {@code AbsColumn}<br>
     *             {@code Searchable}<br>
     *             {@code String}(earch char is symbol) <br>
     *             {@code String}(value) <br>
     *             {@code SQLString}(value) <br>
     *             {@code Number}
     */
    public Expression(Object... objs) {
        this.objs = objs;
    }

    @Override
    public void toSql(StringBuilder sb) {
        boolean f = true;
        for (Object obj : objs) {
            if (f) {
                f = false;
            } else {
                sb.append(' ');
            }
            if (obj instanceof AbstractColumn) {
                ((AbstractColumn) obj).toSql(sb);
            } else if (obj instanceof String) {
                String str = (String) obj;
                if (allSymbol(str)) {
                    sb.append(str);
                } else {
                    SQLString.appendValue(sb, str);
                }
            } else {
                SQLString.appendValue(sb, obj);
            }
        }
    }

    private boolean allSymbol(String str) {
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (!isSymbol(c)) {
                return false;
            }
        }
        return true;
    }

    private boolean isSymbol(char c) {
        for (char s : SYMBOL) {
            if (s == c) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void nameInColumn(StringBuilder sql) {
        if (nameAlias == null) {
            toSql(sql);
        } else {
//            sql.append('(');
            toSql(sql);
            sql.append(" AS ");
            SQLString.appendColumn(sql, nameAlias);
        }
    }

}
